<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
              <a-form-item>
                 <template #label><span title="人员需求编号">人员需求编号</span></template>
                 <j-input placeholder="人员需求编号" v-model:value="queryParam.oaReqNo" allowClear></j-input>
              </a-form-item>
            </a-col>
          <a-col :lg="6">
            <a-form-item name="projectId">
              <template #label><span title="项目名称">项目名称</span></template>
              <j-dict-select-tag placeholder="请选择项目名称" v-model:value="queryParam.projectId" dictCode="tm_project,project_name,id" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="departId">
              <template #label><span title="需求部门">需求部门</span></template>
              <j-search-select placeholder="请选择需求部门" v-model:value="queryParam.departId" dict="sys_depart where org_type='2',depart_name,id" allowClear/>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="6">
              <a-form-item>
                 <template #label><span title="采购需求编号">采购需求编号</span></template>
                 <j-input placeholder="采购需求编号" v-model:value="queryParam.oaReqNo" allowClear></j-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="positionId">
                <template #label><span title="需求岗位">需求岗位</span></template>
                <j-search-select placeholder="请选择需求岗位" v-model:value="queryParam.positionId" dict="tm_position,position_name,id" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="positionLevel">
                <template #label><span title="岗位级别">岗位级别</span></template>
                <j-dict-select-tag placeholder="请选择岗位级别" v-model:value="queryParam.positionLevel" dictCode="position_level" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="reqContract">
                <template #label><span title="招聘对接人">项目负责</span></template>
                <j-search-select placeholder="请选择招聘对接人" v-model:value="queryParam.reqContract" dict="sys_user,realname,username" allowClear/>
              </a-form-item>
            </a-col>
            <!-- <a-col :lg="6">
              <a-form-item name="reqContractMobile">
                <template #label><span title="电话">电话</span></template>
                <a-input placeholder="请输入电话" v-model:value="queryParam.reqContractMobile" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="reqContractEmail">
                <template #label><span title="邮箱">邮箱</span></template>
                <j-input placeholder="请输入邮箱" v-model:value="queryParam.reqContractEmail" allowClear></j-input>
              </a-form-item>
            </a-col> -->
            <a-col :lg="6">
              <a-form-item name="workPlace">
                <template #label><span title="工作地点">工作地点</span></template>
                <j-search-select placeholder="请选择工作地点" v-model:value="queryParam.workPlace" dict="tm_work_place,work_place,id" allowClear/>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item>
                 <template #label><span title="开始时间">开始时间</span></template>
                 <div style="display: flex">
                   <a-form-item name="startDate_begin" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择开始日期" v-model:value="queryParam.startDate_begin" class="query-group-cust" allowClear/>
                   </a-form-item>  
                   <span class="query-group-split-cust">~</span>
                   <a-form-item name="startDate_end" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择结束日期" v-model:value="queryParam.startDate_end" class="query-group-cust" allowClear/>
                   </a-form-item>
                 </div>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item>
                 <template #label><span title="结束时间">结束时间</span></template>
                 <div style="display: flex">
                   <a-form-item name="endDate_begin" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择开始日期" v-model:value="queryParam.endDate_begin" class="query-group-cust" allowClear/>
                   </a-form-item>  
                   <span class="query-group-split-cust">~</span>
                   <a-form-item name="endDate_end" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择结束日期" v-model:value="queryParam.endDate_end" class="query-group-cust" allowClear/>
                   </a-form-item>
                 </div>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="reqStatus">
                <template #label><span title="状态">状态</span></template>
                <j-dict-select-tag placeholder="请选择状态" v-model:value="queryParam.reqStatus" dictCode="req_status" allowClear/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" @row-dbClick="handleDetail"  @edit-end="handleEditEnd" @edit-cancel="handleEditCancel" :beforeEditSubmit="beforeEditSubmit">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 发布需求</a-button>
        <!-- <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button> -->
        <!-- <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button> -->
        <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandlePublish">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    发布
                  </a-menu-item>
                  <a-menu-item key="1" @click="batchHandleOff">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    下架
                  </a-menu-item>
                  <a-menu-item key="1" @click="batchHandleStop">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    中止
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown> -->
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex==='reqDesc'">
          <!--富文本件字段回显插槽-->
          <div v-html="text"></div>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <PositionReqModal ref="registerModal" @success="handleSuccess"></PositionReqModal>
     <!-- 抽屉 -->
     <PositionReqDrawer @register="registerDrawer" @success="handleSuccess" :showFooter="showFooter"></PositionReqDrawer>
     <PositionReqRestartModal ref="registerRestartModal" @success="handleSuccess"></PositionReqRestartModal>
     <PostionReqLockResumeDrawer @register="registerLockPostionReqDrawer" @success="handleSuccess" :showFooter="showFooter"></PostionReqLockResumeDrawer>

  </div>
</template>

<script lang="ts" name="tm-positionReq" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './PositionReq.data';
  import { verifyCopy, list, publish,batchPublish,stop,batchStop,offReq,batchOffReq,deleteOne, batchDelete,checkRestart,restart, getImportUrl, getExportUrl } from './PositionReq.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import PositionReqModal from './components/PositionReqModal.vue'
  
  import PositionReqRestartModal from './components/PositionReqRestartModal.vue'
  import PositionReqDrawer from './components/PositionReqDrawer.vue'
  import PostionReqLockResumeDrawer from './components/PostionReqLockResumeDrawer.vue'
  import { useUserStore } from '/@/store/modules/user';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import {useDrawer} from "@/components/Drawer";
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import JInput from '/@/components/Form/src/jeecg/components/JInput.vue';

    // 复制内容
  const valueRef = ref('');
  const { createMessage } = useMessage();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerLockPostionReqDrawer, { openDrawer: openLockPostionReqDrawer }] = useDrawer();
  const showFooter = ref(true);
  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const registerRestartModal = ref();
  const userStore = useUserStore();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '人力需求池',
      api: list,
      columns,
      // size:'small',//紧凑型表格
      striped:true,//斑马纹设置
      canResize:true,
      useSearchForm: false,
      actionColumn: {
        width: 200,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "人力需求池",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4, //4
    xl:6,
    xxl:8
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  const showFlag = ref(false);
  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);
  function testShow(){
    showFlag.value = false;
  }
  testShow();
  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }
   // 复制
   function handleCopy(record: Recordable) {
    verifyCopy(record.id).then((res)=>{
      if(res) {
        const newlineText = 
        "项目名称："+record.projectId_dictText + "\n" 
      + "岗位名称："+ record.positionId_dictText +"(" +record.positionCount+ ")人" + "\n"
      + "用人周期：" + record.startDate +"到" + record.endDate+ "\n"
      + "工作地点：" + record.workPlace_dictText + "(" + record.workPlaceAddress+ ")\n"
      + "简历接收人：" + record.reqContractUser + "\n" 
      + "岗位要求：\n" + record.reqDesc.replace("<p>","").replace("</p>","").replaceAll("<br>","\n");
      const { isSuccessRef } = useCopyToClipboard(newlineText);
      createMessage.success('拷贝成功');
      }
    });
    
    }

  // 模拟将指定数据保存
  function feakSave({ value, key, id }) {
      createMessage.loading({
        content: `正在模拟保存${key}`,
        key: '_save_fake_data',
        duration: 0,
      });
      return new Promise((resolve) => {
        setTimeout(() => {
          if (value === '') {
            createMessage.error({
              content: '保存失败：不能为空',
              key: '_save_fake_data',
              duration: 2,
            });
            resolve(false);
          } else {
            createMessage.success({
              content: `记录${id}的${key}已保存`,
              key: '_save_fake_data',
              duration: 2,
            });
            resolve(true);
          }
        }, 2000);
      });
    }
  function handleEditEnd({ record, index, key, value }) {
      console.log(record, index, key, value);
      return false;
    }
    async function beforeEditSubmit({ record, index, key, value }) {
      console.log('单元格数据正在准备提交', { record, index, key, value });
      return await feakSave({ id: record.id, key, value });
    }

    function handleEditCancel() {
      console.log('cancel');
    }
  /**
   * 新增事件
   */
  function handleAdd() {
    //registerModal.value.disableSubmit = false;
    // registerModal.value.add();
    showFooter.value = true;
    openDrawer(true, {
      isUpdate: false,
      disableSubmit:false,
    });
  }

  function handleNewReq(record: Recordable) {
    showFooter.value = true;
    openDrawer(true, {
      record,
      disableSubmit:false,
      isUpdate: false,
      isCopyUpdate : true,
      showFooter: false,
    });

  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    // registerModal.value.disableSubmit = false;
    // registerModal.value.edit(record);
    showFooter.value = true;
    openDrawer(true, {
      record,
      disableSubmit:false,
      isUpdate: true,
      showFooter: false,
    });
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    // registerModal.value.disableSubmit = true;
    // registerModal.value.edit(record);
    showFooter.value = false;
    openDrawer(true, {
      record,
      disableSubmit:true,
      isUpdate: true,
      showFooter: false,
    });
  }
   /**
   * 发布
   * @param record
   */
  async function handlePublish(record: Recordable) {
    console.log('publish...');
    await publish({id: record.id},handleSuccess);
   }

  /**
   * 批量发布
   */
  async function batchHandlePublish() {
     await batchPublish({ids: selectedRowKeys.value},handleSuccess);
   }

  /**
   * 停止
   * @param record
   */
  async function handleStop(record: Recordable) {
    await stop({id: record.id}, handleSuccess);
  }

  /**
   * 下架
   */
  async function handleOff(record: Recordable) {
    await offReq({id: record.id}, handleSuccess);
  }

  /**
   * 批量停止
   */
   async function batchHandleOff() {
    await batchOffReq({ids: selectedRowKeys.value},handleSuccess);
  }
  /**
   * 批量停止
   */
  async function batchHandleStop() {
    await batchStop({ids: selectedRowKeys.value},handleSuccess);
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 重启
   */
   function handleRestart(record: Recordable) {
    checkRestart(record.id).then((res) => {
       console.log(res)
       if(res) {
          registerRestartModal.value.disableSubmit = false;
          registerRestartModal.value.edit(record);
       }
    });

  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
  function showLockPostionReq(record: Recordable) {
      showFooter.value = false;
      openLockPostionReqDrawer(true, {
       record,
       disableSubmit:true,
       isUpdate: true,
       showFooter: false,
     });
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
    {
      label: '拷贝',
      onClick: handleCopy.bind(null, record),
    },
    {
      label: '发布',
      show:true,
      disabled: record.reqStatus != "1",
      popConfirm: {
        title: '是否确认发布',
        confirm: handlePublish.bind(null, record),
        placement: 'topLeft',
      },
      // ifShow: (_action) => {
      //     return record.reqStatus == "1"; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
      // },
      auth: 'tm:tm_position_req:publish',
    },
    {
      label: '暂停',
      disabled: record.reqStatus != "2"  && record.reqStatus != "5" ,
      popConfirm: {
        title: '是否确认暂停',
        confirm: handleStop.bind(null, record),
        placement: 'topLeft',
      }
    },
    ];
  }
   
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
       
         {
           label: '下架',
           disabled: record.reqStatus != "1" && record.reqStatus != "2" && record.reqStatus != "3" && record.reqStatus != "5" ,
           popConfirm: {
             title: '是否确认下架',
             confirm: handleOff.bind(null, record),
             placement: 'topLeft',
           }
         },
         {
           label: '重启',
           disabled: record.reqStatus != "4" && record.reqStatus != "3",
           popConfirm: {
             title: '是否确认重启',
             confirm: handleRestart.bind(null, record),
             placement: 'topLeft',
           }
         },
         {
        label: '已锁定简历',
        onClick: showLockPostionReq.bind(null, record),
        }, 
        {
        label: '编辑',
        disabled: record.reqStatus != "0" && record.reqStatus != "1" && record.reqStatus != "4",
          onClick: handleEdit.bind(null, record),
        },
        {
        label: '详情',
        onClick: handleDetail.bind(null, record),
        },
        {
        label: '新需求',
        onClick: handleNewReq.bind(null, record),
        }
      // {
      //   label: '删除',
      //   popConfirm: {
      //     title: '是否确认删除',
      //     confirm: handleDelete.bind(null, record),
      //     placement: 'topLeft',
      //   }
      // }
    ]
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
  



</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
</style>
